package com.hhit.collaborative_learning.utils;

import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.Timestamp;
import java.util.Date;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

public class JsonUtil {

	public static JSONObject formatRsToJSONObject(ResultSet rs)throws Exception{
		ResultSetMetaData md = rs.getMetaData();
		int num = md.getColumnCount();
		JSONObject mapOfColValues = new JSONObject();
		while(rs.next()){
			for (int i = 1; i <= num; i++) {
				Object o = rs.getObject(i);
				if(o instanceof Timestamp){
					Timestamp nowtime=new Timestamp(System.currentTimeMillis());
					Timestamp time=(Timestamp) o;
					String data=DateUtil.formateTimestamp(nowtime, time);
					mapOfColValues.put(md.getColumnName(i),data);
				}else if (o instanceof Date) {
					mapOfColValues.put(md.getColumnName(i),
							DateUtil.formatDate((Date) o, "yyyy-MM-dd"));
				} 
				else {
					mapOfColValues.put(md.getColumnName(i), rs.getObject(i));
				}
			}
		}
		return mapOfColValues;
	}
	public static JSONArray formatRsToJsonArray(ResultSet rs) throws Exception {
		ResultSetMetaData md = rs.getMetaData();
		int num = md.getColumnCount();
		JSONArray array = new JSONArray();
		while (rs.next()) {
			JSONObject mapOfColValues = new JSONObject();
			for (int i = 1; i <= num; i++) {
				Object o = rs.getObject(i);
				if(o instanceof Timestamp){
					Timestamp nowtime=new Timestamp(System.currentTimeMillis());
					Timestamp time=(Timestamp) o;
					String data=DateUtil.formateTimestamp(nowtime, time);
					mapOfColValues.put(md.getColumnName(i),data);
				}
				else if (o instanceof Date) {
					mapOfColValues.put(md.getColumnName(i),
							DateUtil.formatDate((Date) o, "yyyy-MM-dd"));
				} else {
					mapOfColValues.put(md.getColumnName(i), rs.getObject(i));
				}
			}
			array.add(mapOfColValues);
		}
		return array;
	}
}
